package com.bto.leasetest.service;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.bto.leasetest.dao.LeaseReviewTestService;
import com.bto.leasetest.entity.LeaseReviewTest;
import com.bto.leasetest.request.LeaseApprovalNotifyReq;
import com.bto.leasetest.utils.DateUtils;
import com.bto.leasetest.utils.IdUtils;
import com.bto.leasetest.utils.LogUtils;
import com.bto.leasetest.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Slf4j
@Service
public class LeaseService {

    @Value("${order.server-url}")
    public String url;
    @Value("${order.enable}")
    public boolean enable;
    @Autowired
    public LeaseReviewTestService leaseReviewTestService;

    @Async
    public void asyncExecute(LeaseReviewTest leaseReviewTest) {
        try {
            if (enable) {
                Thread.sleep(10000);
            }
            pustHttpRequest(leaseReviewTest);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    @Async
    public void asyncExecute(LeaseReviewTest leaseReviewTest, long time) {
        try {
            if (enable) {
                Thread.sleep(time);
            }
            pustHttpRequest(leaseReviewTest);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void syncExecute(LeaseReviewTest leaseReviewTest) {
        pustHttpRequest(leaseReviewTest);
    }

    public void pustHttpRequest(LeaseReviewTest leaseReviewTest) {
        leaseReviewTestService.updateById(leaseReviewTest);
        LeaseApprovalNotifyReq leaseApprovalNotifyReq = new LeaseApprovalNotifyReq();

        LeaseApprovalNotifyReq.Body.PrjDocumentStatusDto prjDocumentStatusDto =
                new LeaseApprovalNotifyReq.Body.PrjDocumentStatusDto();
        if (StringUtils.isNotBlank(leaseReviewTest.getBusinessKey())) {
            prjDocumentStatusDto.setPartnersContractNumber(leaseReviewTest.getBusinessKey());
        } else if (StringUtils.isNotBlank(leaseReviewTest.getIdCardNo())) {
            prjDocumentStatusDto.setIdCardNo(leaseReviewTest.getIdCardNo());
        }
        LeaseApprovalNotifyReq.Body body = new LeaseApprovalNotifyReq.Body();
        body.setPrjDocumentStatusDto(prjDocumentStatusDto);

        LeaseApprovalNotifyReq.PrjProjectOperatingLeaseStatus prjProjectOperatingLeaseStatus
                = new LeaseApprovalNotifyReq.PrjProjectOperatingLeaseStatus();
        BeanUtils.copyProperties(leaseReviewTest, prjProjectOperatingLeaseStatus);

        LeaseApprovalNotifyReq.Head head = new LeaseApprovalNotifyReq.Head();
        head.setSerialNumber(IdUtils.fastSimpleUUID());
        head.setErrorMessage(null);
        head.setSystemId("YX-GDBT");
        head.setTransactionCode("YX_FINANCE_PROJECT_OL_STATUS_SEND_SIT");
        head.setTransactionTime(DateUtils.dateTimeNow("yyyyMMdd HH:mm:ss"));
        head.setErrorMessage("同步状态");
        head.setErrorCode("01");
        head.setVersion(1);

        leaseApprovalNotifyReq.setBody(Collections.singletonList(body));
        leaseApprovalNotifyReq.setHead(head);
        leaseApprovalNotifyReq.setPrjProjectOperatingLeaseStatus(prjProjectOperatingLeaseStatus);
        String jsonString = JSON.toJSONString(leaseApprovalNotifyReq);

        LogUtils.leaseLogger.info("========================================== 回调Start ==========================================");
        LogUtils.requsetLogger.info("URL            : {}", url);
        LogUtils.requsetLogger.info("Request Args   : {}", JSON.toJSONString(leaseApprovalNotifyReq, JSONWriter.Feature.PrettyFormat));
        long startTime = System.currentTimeMillis();
        LogUtils.requsetLogger.info(DateUtils.dateTimeNow("yyyy-MM-dd HH:mm:ss"));

        String result = HttpRequest.post(url)
                .body(jsonString)
                .timeout(20000)//超时，毫秒
                .execute().body();

        LogUtils.requsetLogger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        LogUtils.requsetLogger.info("Response Args   : {}", JSON.toJSONString(result, JSONWriter.Feature.PrettyFormat));
    }
}
